from flask import Blueprint, request, jsonify
import sqlalchemy.exc
from Model.models import User, db, UserRole
from Utils import AESUtil, JWTUtil
from Utils.APIResponse import APIResponse
from Utils.TokenUtil import token_required

# 导入 Flask 中的蓝图 Blueprint 模块

user_blue = Blueprint("user", __name__)


# 实例化一个蓝图(Blueprint)对象

# 注册用户
@user_blue.route('/user/register', methods=['POST'])
def register_user():
    data = request.json
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return APIResponse.error({'error': 'Username and password are required.'})

    try:
        user = User(username=username, password=AESUtil.AES_en(password), role=UserRole.USER)
        db.session.add(user)
        db.session.commit()
        return APIResponse.success(message={'message': 'User registered successfully.'})
    except sqlalchemy.exc.SQLAlchemyError as e:
        db.session.rollback()
        return APIResponse.error({'error': 'Error registering user: ' + str(e)}, 500)


# 用户登录
@user_blue.route('/user/login', methods=['POST'])
def login_user():
    data = request.json
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return APIResponse.error({'error': 'Username and password are required.'})

    user = User.query.filter_by(username=username).first()
    if user and user.password == AESUtil.AES_en(password):
        user.token = JWTUtil.generate_token({"id": user.id}, 60 * 24)
        try:
            db.session.commit()
            return APIResponse.success(message={'message': 'Login successful.'}, data={
                'token': user.token,
                'id': user.id
            })
        except sqlalchemy.exc.SQLAlchemyError as e:
            db.session.rollback()
            return APIResponse.error({'error': 'Error logining : ' + str(e)}, status_code=500)

    else:
        return APIResponse.error(message={'error': 'Invalid username or password.'}, status_code=401)


# 删除用户
@user_blue.route('/user/delete/<int:user_id>', methods=['DELETE'])
@token_required
def delete_user(user_id, request_user_id):
    request_user = User.query.get(request_user_id)
    user = User.query.get(user_id)
    if user and (request_user.id == user.id or request_user.role.value == UserRole.ADMIN.value):
        try:
            db.session.delete(user)
            db.session.commit()
            return APIResponse.success(message={'message': 'User deleted successfully.'})
        except sqlalchemy.exc.SQLAlchemyError as e:
            db.session.rollback()
            return APIResponse.error(message=jsonify({'error': 'Error deleting user: ' + str(e)}), status_code=500)
    else:
        return APIResponse.error({'error': 'User not found.'}, 404)


# 更新用户信息
@user_blue.route('/user/update/<int:user_id>', methods=['PUT'])
@token_required
def update_user(user_id, request_user_id):
    request_user = User.query.get(request_user_id)
    user = User.query.get(user_id)
    if user and (request_user.id == user.id or request_user.role.value == UserRole.ADMIN.value):
        data = request.json
        new_username = data.get('username')
        new_password = data.get('password')

        if not new_username and not new_password:
            return APIResponse.error(message={'error': 'Username and password are required.'})

        user.username = new_username
        user.password = AESUtil.AES_en(new_password)

        try:
            db.session.commit()
            return APIResponse.success(message={'message': 'User updated successfully.'})
        except sqlalchemy.exc.SQLAlchemyError as e:
            db.session.rollback()
            return APIResponse.error({'error': 'Error updating user: ' + str(e)}, status_code=500)
    else:
        return APIResponse.error({'error': 'User not found.'}, 404)
